/**
 * Created with JetBrains PhpStorm.
 * User: otarim!
 * Date: 12-8-16
 * Time: 上午11:35
 * To change this template use File | Settings | File Templates.
 * if(!(node = $(node))){return false}
 */
(function(){
    /*判断是否存在*/
    if(!window.OTA){
        window['OTA'] = {}
    }
    /*兼容性*/
    function isCompatible(other) {

    }
    window['OTA']['isCompatible'] = isCompatible;
    function $(selection) {
        var id = /^#/g;
        var cla = /^\./g;
        var com = /^[a-z]/i;
        if(typeof selection === 'string'){
            if(id.test(selection)){
                var node = selection.slice(1,selection.length);
                return document.getElementById(node);
            }else
            if(cla.test(selection)){
                if(document.getElementsByClassName){
                    return document.getElementsByClassName(node);
                }else{
                    getElementsByClassName(node);
                }
            }else
            if(com.test(selection)){
                return document.getElementsByTagName(selection);
            }
        }else
        if(selection == window){
            return window;
        }
        return false;
    }
    window['OTA']['$'] = $;
    /**
     * 由于this指向不同（一个是元素，一个是window，需要通过匿名函数绑定至事件源本身）
     *
     */
    function addEvent(node,type,listener) {
        if(node.addEventListener){
            node.addEventListener(type,listener,false);/*返回这个操作faslse 默认操作*/
            return true;
        }else{
            if(node.attachEvent){
                node.attachEvent('on'+type,listener);
                return true;
            }
        }
        return false;
    }
    window['OTA']['addEvent'] = addEvent;
/*取消监听*/
    function removeEvent(node,type,listener) {
//        if(!isCompatible()){return false};
        if(!(node = $(node))){return false}/*这里的node需要document获取到，如果不是则返回false*/
        if(node.removeEventListener){
            node.removeEventListener(type,listener,false);/*返回这个操作*/
            return true;
        }else{
            if(node.detachEvent){
                node.detachEvent('on'+type,listener);
                return true;
            }
        }
        return false;
    }
    window['OTA']['removeEvent'] = removeEvent;
    function addLoadEvent(loadEvent,waitImg) {
        if(waitImg){/*等待*/
            return addEvent(window,'load',loadEvent)
        }
        var init = function() {
            if(arguments.callee.done){
                return;
            }
            arguments.callee.done = true;
            loadEvent.apply(document,arguments);/*这里的arguments....*/
        }
        if(document.addEventListener){
            document.addEventListener("DOMContentLoaded",init,false)
        }
        if(/Webkit/i.test(navigator.userAgent)){
            var _time = setInterval(function(){
                if(/loaded | complete/.test(document.readyState)){
                    clearInterval(_time);
                    init();
                }
            },10)
        }
        // For Internet Explorer (using conditional comments) attach a script
        // that is deferred to the end of the load process and then check to see
        // if it has loaded
        /*@cc_on @*/
        /*@if (@_win32)
         document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
         var script = document.getElementById("__ie_onload");
         script.onreadystatechange = function() {
         if (this.readyState == "complete") {
         init();
         }
         };
         /*@end @*/
        return true;
    }
    window['OTA']['addLoadEvent'] = addLoadEvent;
/*获取class*/
    function getElementsByClassName(classname) {
//        if(!(node == $(node))){return false};
        var doms = [];
        var tags = document.all || document.getElementsByTagName("*");
        /*使用正则表达式匹配classname*/
        classname = classname.replace(/\-/g, "\\-");
        var regex = new RegExp("(^|\\s)" + classname + "(\\s|$)");
        for(var i = 0;i<tags.length;i++){
            if(regex.test(tags[i].className)){
                doms.push(tags[i])
            }
        }
        return doms;
    }
    window['OTA']['getElementsByClassName'] = getElementsByClassName;
/*切换show，hidden*/
    function toggleDisplay(node) {
        if(node.style.display == 'none'){
            node.style.display = 'block';
        }else{
            node.style.display = 'none';
        }
    }
    window['OTA']['toggleDisplay'] = toggleDisplay;
/*insertAfter*/
    function insertAfter(node,referenceNode) {
//        if(!(node == $(node))){return false};
        /*判断节点nodetype*/
        var lastChild = referenceNode.parentNode.lastChild.nodeType == 1 ? referenceNode.parentNode.lastChild : referenceNode.parentNode.lastChild.previousSibling;
        if(referenceNode == lastChild){
            referenceNode.parentNode.appendChild(node);
        }else{
            referenceNode.parentNode.insertBefore(node,referenceNode.nextSibling);
        }
    }
    window['OTA']['insertAfter'] = insertAfter;
/*删除节点*/
    function removeChildren(parent) {
        /*使用while循环，只要有firstChild就删除*/
        while(parent.firstChild){
            parent.removeChild(parent.firstChild);
        }
        return parent;
    }
    window['OTA']['removeChildren'] = removeChildren;
/*删除节点*/
    function prependChild(parent,child) {
        if(parent.firstChild){
            parent.insertBefore(child,parent.firstChild);
        }else{
            parent.appendChild(child);
        }
    }
    window['OTA']['prependChild'] = prependChild;
/*构造函数mylog*/
    function myLog() {
        var createWindow = function () {
            var size = getBrowserWindowSize();
            var top = size.height * 0.5 - 120 || 0;
            var left = size.width * 0.5 - 200 || 0;
            /*无法访问,需要定义为全局*/
            node = document.createElement('ul');
            node.setAttribute('id','oWindow');
            node.style.width = '400px';
            node.style.height = '240px';
            node.style.border = '1px solid #999';
            node.style.overflow = 'auto';
            node.style.position = 'absolute';
            node.style.top = top + 'px';
            node.style.left = left + 'px';
            node.style.backgroundColor = 'white';
            node.style.listStyle = 'none';
            node.style.padding = '0';
            node.style.margin = '0';
            document.body.appendChild(node);
        }
        this.writeRaw = function (message) {
            if(!$("oWindow")){
                createWindow();
            }
            var li = document.createElement('li');
            li.style.padding = '2px 4px';
            li.style.border = '0';
            li.style.borderBottom = '1px dashed #ccc';
            li.style.margin = '0';
            li.style.font = '10px/1.4 monaco';
            li.style.color = "#555";
            /*判断有无错误信息*/
            if(typeof message === 'undefined'){
                var text = document.createTextNode("Message is undefined");
            }else{
                var text = document.createTextNode(message);
            }
            li.appendChild(text);
            node.appendChild(li);
            return this;
        }
    }
    myLog.prototype = {
        write : function(message){
            if(typeof message == 'string' && message.length == 0){
                return this.writeRaw('null message');
            }
            if(typeof message !== 'string'){
                /*null 没有 tostring 方法*/
                if(message !== null && message !== undefined && message.toString){
                /*console.log(object)*/
                    return this.writeRaw(message.toString());
                }else{
                    return this.writeRaw(typeof message);
                }
            }
            // transform < and > so that .innerHTML doesn't parse the message as HTML
            message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;");/*级联*/
            return this.writeRaw(message);
        }
    }
    window['OTA']['log'] = new myLog();
    function getBrowserWindowSize() {
        /*返回包含width，height属性的对象*/
        return  {
            width : window.innerWidth || document.body.clientWidth || (document.documentElement && document.documentElement.clientWidth),
            height : window.innerHeight || document.body.clientHeight || (document.documentElement && document.documentElement.clientHeight),
        }
    }
    window['OTA']['getBrowserWindowSize'] = getBrowserWindowSize;
    window['OTA']['node'] = {
        ELEMENT_NODE                : 1,
        ATTRIBUTE_NODE              : 2,
        TEXT_NODE                   : 3,
        CDATA_SECTION_NODE          : 4,
        ENTITY_REFERENCE_NODE       : 5,
        ENTITY_NODE                 : 6,
        PROCESSING_INSTRUCTION_NODE : 7,
        COMMENT_NODE                : 8,
        DOCUMENT_NODE               : 9,
        DOCUMENT_TYPE_NODE          : 10,
        DOCUMENT_FRAGMENT_NODE      : 11,
        NOTATION_NODE               : 12
    }
    /*trim*/
    if(!String.trim){
        String.prototype.trim = function(){
            return this.replace(/^\s+|\s+$/g,'')/*\s+表示多个空格 | 表示或者*/
        }
    }
    /*repeat*/
    if(!String.repeat){
        String.prototype.repeat = function(l){
            return new Array(l+1).join(this)/*用this连接l字符串*/
        }
    }
    /*cancelBubble,not preventDefault*/
    function stopPropagation(e) {
        e = e || window.event;
        if(e.stopPropagation){
            e.stopPropagation();
        }else{
            e.cancelBubble = true;/*for ie*/
        }
    }
    window['OTA']['stopPropagation'] = stopPropagation;
    /*preventDefault*/
    function preventDefault(e) {
        e = e || window.event;
        if(e.preventDefault){
            e.preventDefault();
        }else{
            e.returnValue = false;/*for ie*/
        }
    }
    window['OTA']['preventDefault'] = preventDefault;
    /*e*/
    function getEventObject(event) {
        return  event || window.event;
    }
    window['OTA']['getEventObject'] = getEventObject;
    /*eventTarget*/
    function getTarget(eventObject) {
        var eventObject = eventObject || window.event;
        var target = eventObject.srcElement || eventObject.target;
        if(target.nodeType == OTA.node.TEXT_NODE){
            target = target.parentNode;
        }
        return target;
    }
    window['OTA']['getTarget'] = getTarget;
    function getMouseButton() {
        /*
        * p182
        *
        * */
    }
    window['OTA']['getMouseButton'] = getMouseButton;
    /*返回相对于文档的位置*/
    function getPointerPosition(eventObject) {
        var eventObject = eventObject || window.event;
        /*safari --> common*/
        var x = eventObject.pageX || (eventObject.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
        var y = eventObject.pageY || (eventObject.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
        return {
            x: x,
            y: y
        }
        /*返回一个对象*/
    }
    window['OTA']['getPointerPosition'] = getPointerPosition;
    /*scrollPosition*/
    function getScrollPosition() {
        var x = document.documentElement.scrollLeft || document.body.scrollLeft;
        var y = document.documentElement.scrollTop || document.body.scrollTop;
        return {
            x: x,
            y: y
        }
    }
    window['OTA']['getScrollPosition'] = getScrollPosition;
})()
